//
//  TopicDetailUgcTableView.m
//  ZITHER
//
//  Created by 吴凡 on 2019/2/18.
//  Copyright © 2019 weixn. All rights reserved.
//

#import "TopicDetailUgcTableView.h"

#import "Ugc_Friends_OnePicCell_WX.h"
#import "Ugc_Friends_FourPicCell_WX.h"
#import "Ugc_Friends_MorePicCell_WX.h"
#import "MainFirst_MagazineList_PGCCell_WX.h"
#import "MainFirst_MagazineList_UgcCell_WX.h"

#import "MainFirst_Magazine_VC_WX.h"
#import "Ugc_Detail_VC_WX.h"
#import "UgcMainModel.h"

#import "CRBBoxHomeHttp.h"
#import "TopicDetailModel.h"

@implementation TopicDetailUgcTableView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self defaultConfiguration];
    }
    return self;
}

-(void)setIndexType:(NSString *)indexType{
    _indexType = indexType;
    [self.mj_header beginRefreshing];
}

-(void)loadData:(BOOL)type sort:(int)sort{
  //  @weakify(self);
    
    [CRBBoxHomeHttp requestTopicDetailUgcListWithPage:@(self.page+1) size:@(8) sort:@(sort) topicId:_topicId success:^(NSURLSessionDataTask *task, id responseObject) {
        
        TopicDetailModel *topicDetailModel = (TopicDetailModel *)responseObject;
        
        if (topicDetailModel.list.count == 0) {
            if (self.page == 0) {
                [Tools showTips:@"暂无更多数据"];
                [self.mj_header endRefreshing];
                [self.mj_footer endRefreshing];
            }else{
                [self.mj_footer endRefreshingWithNoMoreData];
            }
            return ;
        }
        
        NSArray *arr = topicDetailModel.list;
        if (type) {
            self.arrM = [[NSMutableArray alloc]init];
            [[SDImageCache sharedImageCache] clearMemory];
        }
        for (UgcMainModel *model in arr) {
            [self.arrM addObject: model];
        }
        [self reloadData];
        [self.mj_header endRefreshing];
        [self.mj_footer endRefreshing];
        
    } fail:^(NSURLSessionDataTask *task, NSError *error, NSString *code, NSString *msg) {
        [self.mj_header endRefreshing];
        [self.mj_footer endRefreshing];
        [Tools showTips:msg];
    }];
    
//    if ([self.indexType isEqualToString:@"2"]) {
//        [[serviceDefualt loadGetuserUgcList:@"" isEssence:self.indexType page:self.page reponseObjctClass:[UgcMainModel class]]subscribeNext:^(ResponseData * x) {
//            @strongify(self);
//            if (x.success) {
//
//                NSArray *arr1 = x.responseRawData[@"data"][@"list"];
//
//                if (arr1.count == 0) {
//                    if (self.page == 0) {
//                        [Tools showTips:@"暂无更多数据"];
//                        [self.mj_header endRefreshing];
//                        [self.mj_footer endRefreshing];
//                    }else{
//                        [self.mj_footer endRefreshingWithNoMoreData];
//                    }
//                    return ;
//                }
//
//                UgcMainModel *model = x.responseData;
//                NSArray *arr = model.list;
//
//                if (type) {
//                    self.arrM = [[NSMutableArray alloc]init];
//                    [[SDImageCache sharedImageCache] clearMemory];
//                }
//
//                for (UgcMainModel *model in arr) {
//                    [self.arrM addObject: model];
//                }
//                [self reloadData];
//
//            }else{
//                [Tools showTips:x.errorInfo];
//            }
//            [self.mj_header endRefreshing];
//            [self.mj_footer endRefreshing];
//
//        }];
//    }
    
}


-(void)setHeadV{
    
}

- (void)setSectionStr:(NSString *)sectionStr {
    _sectionStr = sectionStr;
    if (self.sectionView) {
         self.sectionView.titleLabel.text = _sectionStr;
    }
}
-(void)endRefreshing{
    [self.mj_header endRefreshing];
    [self.mj_footer endRefreshing];
}

-(void)defaultConfiguration{
    
    _sort = 2;
    self.delegate = self;
    self.dataSource = self;
    self.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.rowHeight = UITableViewAutomaticDimension;
    self.estimatedRowHeight = 1000;
    [self registerNib:[UINib nibWithNibName:@"UgcFriendsTbvCell" bundle:nil] forCellReuseIdentifier:@"UgcFriendsTbvCell"];
    [self registerNib:[UINib nibWithNibName:@"Ugc_Friends_OnePicCell_WX" bundle:nil] forCellReuseIdentifier:@"Ugc_Friends_OnePicCell_WX"];
    [self registerNib:[UINib nibWithNibName:@"Ugc_Friends_FourPicCell_WX" bundle:nil] forCellReuseIdentifier:@"Ugc_Friends_FourPicCell_WX"];
    [self registerNib:[UINib nibWithNibName:@"Ugc_Friends_MorePicCell_WX" bundle:nil] forCellReuseIdentifier:@"Ugc_Friends_MorePicCell_WX"];
    [self registerNib:[UINib nibWithNibName:@"MainFirst_MagazineList_PGCCell_WX" bundle:nil] forCellReuseIdentifier:@"MainFirst_MagazineList_PGCCell_WX"];
    [self registerNib:[UINib nibWithNibName:@"MainFirst_MagazineList_UgcCell_WX" bundle:nil] forCellReuseIdentifier:@"MainFirst_MagazineList_UgcCell_WX"];
    
    
    @weakify(self);
    self.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self);
        self.page = 0;
        [self loadData:YES sort:self.sort];
    }];
    
    self.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        @strongify(self);
        self.page ++;
        [self loadData:NO sort:self.sort];
    }];
    
}


#pragma MARK - 数据源
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrM.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.indexType isEqualToString:@"2"]) {
        UgcMainListModel *model = self.arrM[indexPath.row];
        
        if (model.fileList.count == 1) {
            return [self getFriendsOneCell:indexPath];
        }else if(model.fileList.count == 4){
            return [self getFriendsFourPicCell:indexPath];
        }else{
            return [self getFriendsMorePicCell:indexPath];
        }
    }
    return nil;
}

-(Ugc_Friends_OnePicCell_WX*)getFriendsOneCell:(NSIndexPath*)indexPath{
    
    static NSString *OnePicCell = @"Ugc_Friends_OnePicCell_WX";
    Ugc_Friends_OnePicCell_WX *cell = [self dequeueReusableCellWithIdentifier:OnePicCell];
    if (cell == nil) {
        cell = [[Ugc_Friends_OnePicCell_WX alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:OnePicCell];
    }
    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    if ([self.indexType isEqualToString:@"2"]) {
        UgcMainListModel *model = self.arrM[indexPath.row];
        cell.model = model;
    }else{
        CoverCreateListModelSub *modelSub = self.model.result.list[indexPath.row];
        cell.modelSub = modelSub;
    }
    
    return cell;
}

-(Ugc_Friends_FourPicCell_WX*)getFriendsFourPicCell:(NSIndexPath*)indexPath{
    
    static NSString *fourPicCell = @"Ugc_Friends_FourPicCell_WX";
    Ugc_Friends_FourPicCell_WX *cell = [self dequeueReusableCellWithIdentifier:fourPicCell];
    if (cell == nil) {
        cell = [[Ugc_Friends_FourPicCell_WX alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:fourPicCell];
    }
    
    @weakify(cell);
    
    @weakify(self);
    
    [cell setShowBigPic:^(NSIndexPath * _Nonnull indexPath, NSUInteger index) {
        @strongify(cell);
        @strongify(self);
        self.type = NO;
        [self.arrImageView removeAllObjects];
        [self.arrImageUrl removeAllObjects];
        
        self.arrZipImageView = cell.arrImageView;
        
        for (int i = 0; i<cell.model.fileList.count; i++) {
            NSString *str = [NSString stringWithFormat:@"%@%@",RootUrlImage,cell.model.fileList[i]];
            UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
            [imageV sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"ucg_img_loding"]];
            [self.arrImageView addObject:imageV];
            [self.arrImageUrl addObject:str];
        }
        
        [self showBigImage:index];
    }];
    
    cell.indexPath = indexPath;
    
    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    
    if ([self.indexType isEqualToString:@"2"]) {
        UgcMainListModel *model = self.arrM[indexPath.row];
        cell.model = model;
    }else{
        CoverCreateListModelSub *modelSub = self.model.result.list[indexPath.row];
        cell.modelSub = modelSub;
    }
    return cell;
}

-(Ugc_Friends_MorePicCell_WX*)getFriendsMorePicCell:(NSIndexPath*)indexPath{
    static NSString *sectionCell = @"Ugc_Friends_MorePicCell_WX";
    //        NSLog(@" ========== %@",sectionCell);
    Ugc_Friends_MorePicCell_WX *cell = [self dequeueReusableCellWithIdentifier:sectionCell];
    if (cell == nil) {
        cell = [[Ugc_Friends_MorePicCell_WX alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:sectionCell];
    }
    cell.indexPath = indexPath;
    @weakify(cell);
    @weakify(self);
    [cell setShowBigPic:^(NSIndexPath * _Nonnull indexPath, NSUInteger index) {
        @strongify(cell);
        @strongify(self);
        self.type = NO;
        [self.arrZipImageView removeAllObjects];
        [self.arrImageView removeAllObjects];
        [self.arrImageUrl removeAllObjects];
        
        for (int i = 0; i<cell.model.fileList.count; i++) {
            NSString *str = [NSString stringWithFormat:@"%@%@",RootUrlImage,cell.model.fileList[i]];
            UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
            [imageV sd_setImageWithURL:[NSURL URLWithString:str] placeholderImage:[UIImage imageNamed:@"ucg_img_loding"]];
            [self.arrImageView addObject:imageV];
            [self.arrImageUrl addObject:str];
            [self.arrZipImageView addObject:cell.arrImageView[i]];
        }
        
        [self showBigImage:index];
    }];
    cell.selectionStyle = UITableViewCellSeparatorStyleNone;
    if ([self.indexType isEqualToString:@"2"]) {
        UgcMainListModel *model = self.arrM[indexPath.row];
        cell.model = model;
    }else{
        CoverCreateListModelSub *modelSub = self.model.result.list[indexPath.row];
        cell.modelSub = modelSub;
        
    }    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([self.indexType isEqualToString:@"2"]) {
        
        UgcMainListModel *model = self.arrM[indexPath.row];
        Ugc_Detail_VC_WX *vc = [[Ugc_Detail_VC_WX alloc]init];
        vc.ugcId = model.ugcId;
        [vc setBlockDel:^{
            [self.arrM removeObjectAtIndex:self.selectCellIndexPath];
            [self deleteRowsAtIndexPaths:@[indexPath]  withRowAnimation:UITableViewRowAnimationFade];
        }];
        [self.getNav pushViewController:vc animated:YES];
        
    }
}
#pragma mark - tableview section
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    _sectionView = [[NSBundle mainBundle]loadNibNamed:@"TopicDetailSectionView" owner:nil options:nil][0];
    
    if (_sectionStr != nil) {
        _sectionView.titleLabel.text = _sectionStr;
    } else  {
        _sectionView.titleLabel.text = @"";
    }
    
    if (_sort == 2) {
        [_sectionView.filerBtn setTitle:@"最新" forState:UIControlStateNormal];
    } else {
        [_sectionView.filerBtn setTitle:@"热门" forState:UIControlStateNormal];
    }
    
    
    __weak typeof(self) weakSelf = self;
    _sectionView.sectionBlock = ^{
        if (weakSelf.sort == 2) {
            weakSelf.sort = 6;
            [weakSelf.sectionView.filerBtn setTitle:@"热门" forState:UIControlStateNormal];
        } else {
            weakSelf.sort = 2;
            [weakSelf.sectionView.filerBtn setTitle:@"最新" forState:UIControlStateNormal];
        }
        [weakSelf.mj_header beginRefreshing];
//        if (weakSelf.sectionBlock) {
//            weakSelf.sectionBlock();
//        }
    };
    return _sectionView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44.f;
}
-(QMUIImagePreviewViewController *)imagePreviewViewController{
    if (!_imagePreviewViewController) {
        _imagePreviewViewController = [[QMUIImagePreviewViewController alloc] init];
        _imagePreviewViewController.imagePreviewView.delegate = self;
    }
    return _imagePreviewViewController;
}

-(void)showBigImage:(NSInteger)selectIndex{
    UIImageView *imageV = self.arrZipImageView[selectIndex];
    @weakify(self);
    self.imagePreviewViewController.customGestureExitBlock = ^(QMUIImagePreviewViewController *aImagePreviewViewController, QMUIZoomImageView *currentZoomImageView) {
        @strongify(self);
        NSInteger index = aImagePreviewViewController.imagePreviewView.currentImageIndex;
        UIImageView *imageV1 = self.arrZipImageView[index];
        
        UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
        CGRect rect=[imageV1 convertRect: imageV1.bounds toView:window];
        
        [aImagePreviewViewController exitPreviewToRectInScreenCoordinate:rect];
        self.imagePreviewViewController = nil;
    };
    self.imagePreviewViewController.imagePreviewView.currentImageIndex =  selectIndex;// 默认查看的图片的 index
    
    UIWindow * window=[[[UIApplication sharedApplication] delegate] window];
    
    CGRect rect=[imageV convertRect: imageV.bounds toView:window];
    
    [self.imagePreviewViewController startPreviewFromRectInScreenCoordinate:rect cornerRadius:imageV.layer.cornerRadius];
}


#pragma mark - <QMUIImagePreviewViewDelegate>

- (NSUInteger)numberOfImagesInImagePreviewView:(QMUIImagePreviewView *)imagePreviewView {
    return self.arrImageView.count;
}

- (void)imagePreviewView:(QMUIImagePreviewView *)imagePreviewView renderZoomImageView:(QMUIZoomImageView *)zoomImageView atIndex:(NSUInteger)index {
    // 模拟异步加载的情况
    zoomImageView.reusedIdentifier = @(index);
    [zoomImageView showLoading];
    if ([zoomImageView.reusedIdentifier isEqual:@(index)]) {
        //        UIImageView *imageV = ;
        [self.arrImageView[index] sd_setImageWithURL:[NSURL URLWithString:self.arrImageUrl[index]] placeholderImage:[UIImage imageNamed:@"ucg_img_loding"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            [zoomImageView hideEmptyView];
            zoomImageView.image = self.arrImageView[index].image;
            
        }];
    }
    
}

- (QMUIImagePreviewMediaType)imagePreviewView:(QMUIImagePreviewView *)imagePreviewView assetTypeAtIndex:(NSUInteger)index {
    return QMUIImagePreviewMediaTypeImage;
}

#pragma mark - <QMUIZoomImageViewDelegate>

- (void)singleTouchInZoomingImageView:(QMUIZoomImageView *)zoomImageView location:(CGPoint)location {
    //点击缩回
    self.imagePreviewViewController.customGestureExitBlock(self.imagePreviewViewController, zoomImageView);
    [self.arrImageView removeAllObjects];
    [self.arrImageUrl removeAllObjects];
    [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
    
}



- (NSMutableArray<UIImageView *> *)arrImageView{
    if (!_arrImageView) {
        _arrImageView = [[NSMutableArray alloc]init];
    }
    return _arrImageView;
}

-(NSMutableArray *)arrZipImageView{
    if (!_arrZipImageView) {
        _arrZipImageView = [[NSMutableArray alloc]init];
    }
    return _arrZipImageView;
}

-(NSMutableArray *)arrImageUrl{
    if (!_arrImageUrl) {
        _arrImageUrl = [[NSMutableArray alloc]init];
        
    }
    return _arrImageUrl;
}

-(Ugc_Friends_TbvHead_WX *)headView{
    if (!_headView) {
        _headView = [[Ugc_Friends_TbvHead_WX alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 200)];
    }
    return _headView;
}

@end
